;( function () {
    "use strict";
   	var param_map = Result.getLocationParamObject();
    var race_id = param_map.race_id;
    var quCode = null;
    var detailObj = null;
    var global_param_map;
    
	 $( function () {
		 App.init();
		 if(!App.checkLogin()){
			 alert("还没有登录");
			 setTimeout(function () {
				Result.forward("../login/login.html", {});
	 		 }, 800);
			 return;
		 }
		 
		 global_param_map = App.getCookeData();
		 $("#head_login_status").empty();
		 $("#_user_name").html(global_param_map["nickname"]);
		 if(global_param_map["user_icon"] !== undefined && global_param_map["user_icon"] != null 
			&& global_param_map["user_icon"] != ""){
			$("#_head_pic").attr("src", Interface.image.pre + global_param_map["user_icon"]);
		 }
		 $("#head_login_status").append($("#already_login_template"));
		 
		 $("#account_").html(global_param_map["mobile"]);
		 $("#nicheng").html(global_param_map["nickname"]);
		 
		 loadByIp();
		 //定位的
		 var cityJson = App.getCity();
		 if(cityJson){
			 $("#local_city").attr("org_code", cityJson.org_code);
			 $("#local_city").attr("org_name", cityJson.org_name);
			 $("#local_city").find("a").html(cityJson.org_name);
			 $("#local_city").removeClass("yes").addClass("yes");
		 } else {
			 $("#local_city").find("a").html("没定位到城市");
			 $("#local_city").removeClass("yes");
		 }
		 //用户正在用的cit
		 var useCityJson = App.getUseCity();
		 if(useCityJson){
			 quCode = useCityJson.org_code;
			 $("#chengshi").html(useCityJson.org_name);
		 }
		 loadAllCity();
		 if(useCityJson){
			 $(".citylist li.yes").removeClass("active");
			 var len = $(".citylist").find("li[org_code="+quCode+"]").length;
			 if(len == 1){
				 $(".citylist li.yes[org_code='"+quCode+"']").removeClass("active").addClass("active");
			 } else if (len > 1) {
				 $(".citylist li.yes[org_code='"+quCode+"']").eq(0).removeClass("active").addClass("active");
			 }
		 }
		 
		 
		 loadDetail();
		 $("#cat_name").html(detailObj.matchType.name);
		 $("#to_race_index").click(function(){
			 Result.forward("raceIndex.html", {"category_id" : detailObj.matchType.id});
		 });
		 
		 $("#to_race_detail").click(function(){
			 Result.forward("raceDetail.html", {"race_id" : race_id});
		 });
		 
		 $("#tijiao").click(function(){
			 tijiao();
		 });
		 
		 $("#lijizhifu").click(function(){
			 var order_no = $("#cp_order").val();
			 var type = $("div.payitem.active").attr("type");
			 var channel_type = 0;
			 if(type == "weixin"){
				 channel_type = 2;
			 } else if (type == "zhifubao") {
				 zhifubaoZhifu(order_no);
			 } else if (type == "yihang") {
				 
			 }
			 //zhifuqu(order_no, channel_type);
			 //alert("我跳到第三方支付,order_no=" + order_no);
			 //onclick="$('#pay-modal').modal('close')"
		 });
	 });
	 
	 
	 
	 
	 function zhifubaoZhifu(order_no){
		//做加密
     	var timeStamp = new Date().getTime().toString();
     	var params = {};
     	params.sign = encodeURIComponent(DES3.encrypt("x/fBeYXQ95Q+Aa7QGYVigzRD",hex_md5(timeStamp).toUpperCase()));
     	params.timestamp =timeStamp;
     	var token =$.cookie(App.getCookieTokenEncrypt());
 		if(typeof(token) === "undefined" || token == null || token == "" || token == "null"){
 			//extParams.token = "";
 		} else {
 			params.token = token;
 		}
 		params.imsi = 'unkown';
 		params.imei = 'unkown';
 		params.system_type = '3';
 		params.client_version = 'unkown';
 		params.longitude = 'unkown';
 		params.latitude = 'unkown';
 		params.model = 'unkown';
 		params.channel_type = 'unkown';
 		params.system_version = '3';
 		params.cp_order = order_no;
 		params.cp_type = 1;
 		params.total_original_fee = detailObj.reg_fee;
 		params.total_real_fee = detailObj.reg_fee;
 		params.goods_name = "智胜报名";
 		params.goods_detail = detailObj.matchType.name;
 		params.is_page = 1;
 		params.pay_channel_type = 1;
 		$('#pay-modal').modal('close');
 		layer.confirm('正在支付中？', {
 			btn: ['已完成支付','支付出现问题'] //按钮
		}, function(){
			Result.forward("raceDetail.html", {"race_id" : race_id});
		}, function(){
			alert("请尝试重新支付或联系管理员");
		});
 		var str = buildQuery(params);
 		var url = Interface.host.zhisheng_api_host_servser + "pay/getPayCertify?" + str;
 		window.open(url);
	 };
	 
	 
	 
	 /**
	  * 生成get标签
	  */
	 function buildQuery(obj){
		var index;
		var query = "";
		for (index in obj){
			query += (index +"=" + obj[index] + "&");
		}
		query = query.substr(0, query.length-1);
		return query;
	 }

	 
	 function zhifuqu(order_no, channel_type){
		 var params = {};
		 params.cp_order = order_no;
		 //params.channel_type = channel_type;
		 params.cp_type = 1;
		 params.total_original_fee = detailObj.reg_fee;
		 params.total_real_fee = detailObj.reg_fee;
		 params.goods_name = "智胜报名";
		 params.goods_detail = detailObj.matchType.name;
		 params.is_page = 1;
		 
		 Result.doResult( {
			 url:  Interface.zs.payGetPayCertify,
			 data: params,
			 type: "POST",
			 async: false,
		 }, function ( data ) {
			 console.log(data);
			 $('#pay-modal').modal('close');
			 var f = layer.open({
				 type: 2,
				 title: '支付页面',
				 shadeClose: false,
				 shade: 0.8,
				 area: ['500px', '300px'],
				 content: data
			 }); 
		 }, function ( desc ) {
			 Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
		 
	 }
	 
	 
	 $("#city-modal").on("focus", "#search_city", function(){
		 var that = $(this);
		 Result.doResult( {
	    	url: Interface.zs.orgGetOrgList,
	       	type: "POST",
	       	async: false,
	       	data : {}
	   	}, function ( data) {
	   		that.autocomplete(data , {  
	   			minChars: 0,
	   	        width: 680,
	   	        autoFill: false,
	            matchContains: true,  
	            highlight : false,
	            scroll : true, // 当结果集大于默认高度时是否使用卷轴显示  
	            formatItem: function(row, i, max) {  
	                 return row.org_name;  
	            },  
	            formatMatch: function(row, i, max) {  
	                 return row.org_name;  
	            },  
	            formatResult: function(row) {
	                return row.org_name;  
	            }  
	        }).result(function(event, row, formatted) {
	        	$(".citylist li.yes").removeClass("active");
	        	quCode = row.org_code;
            	var org_name = row.org_name;
				$("#chengshi").html(org_name);
				$("#city-modal").modal("close");
				//选择完更新缓存
				var jj = {"org_code" : quCode, "org_name" : org_name};
  			  	App.setUseCity(jj);
				var len = $(".citylist").find("li[org_code="+quCode+"]").length;
				 if(len == 1){
					 $(".citylist li.yes[org_code='"+quCode+"']").removeClass("active").addClass("active");
				 } else if (len > 1) {
					 $(".citylist li.yes[org_code='"+quCode+"']").eq(0).removeClass("active").addClass("active");
				 }
            });  
	   	}, function ( desc ) {
	        Result.alert( "对不起:" + desc );
	    }, function ( err ) {
	        Result.alert( "错误:" + JSON.stringify(err));
	    } );
	 });
	 
	 
	 
	 function loadAllCity(){
		var $list = $("#all_city_list"),
			$template = $("#all_city_template");
			$("#host_city").empty();
		Result.doResult( {
        	url: Interface.zs.orgGetOrgList,
           	type: "POST",
           	async: false,
           	data : {}
       	}, function ( data) {
	       	var letterMap = {
	       		"A" : [], "B" : [], "C" : [], "D" :[],  "E" : [], "F" : [], "G" : [], "H" : [],
	       		"I" : [], "J" : [], "K" : [], "L" : [], "M" : [], "N" : [], "O" : [],
	       		"P" : [], "Q" : [], "R" : [], "S" : [], "T" : [], "U" : [], "V" : [],
	       		"W" : [], "X" : [], "Y" : [], "Z" : []
	       	};
	       	if( $.isArray( data ) ) {
	    		for( var i = 0, l = data.length; i < l; i++ ) {
	    			var temp = data[i]["first_letter"].toUpperCase();
	    			letterMap[temp].push(data[i]);
	            }
	    	   for(var i in letterMap){
	    		  var letterList = letterMap[i];
	    		  if(letterList.length == 0){
	    			  continue;
	    		  }
	    		  var obj = $template.clone().removeAttr( "id" );
	    		  obj.find(".letter_fist").html(i);
	    		  obj.find(".citylist").empty();
	    		  for( var j = 0, l = letterList.length; j < l; j++ ) {
	    			  var org_name = letterList[j]['org_name'];
	    			  //填补hot
	    			  if(letterList[j]['is_hot'] == 1){
	    				  var ah = '<li class="yes '+active+'" org_code="'+letterList[j]['org_code']+'" org_name="'+org_name+'"><a >'
		    			  	+org_name+'</a></li>';
	    				  $("#host_city").append(ah);
	    			  }
	    			  
	    			  //当定位没有订到的话，默认一个已开通的城市
	    			  var active = "";
	    			  if(quCode == null || quCode == ""){
	    				  $("#chengshi").html(org_name);
		    			  quCode = letterList[j]['org_code'];
		    			  active = "active";
		    			  //设置默认的缓存
		    			  var jj = {"org_code" : quCode, "org_name" : org_name};
		    			  App.setUseCity(jj);
		    		  }
	    			  var a = '<li class="yes '+active+'" org_code="'+letterList[j]['org_code']+'" org_name="'+org_name+'"><a >'
	    			  	+org_name+'</a></li>';
	    			  obj.find(".citylist").append(a);
	    			  
		          }
	    		  $list.append(obj);
	    	   }
	        }
	       	
	        $(".citylist li.yes").off().click(function(){
		       	 $(".citylist li.yes").removeClass("active");
		       	 $(this).addClass("active");
	        });
	       	
			$("#btn-city-center").on("click",function(){
				var active =  $(".citylist li.active"),
					name = active.attr("org_name"),
					code = active.attr("org_code");
				quCode = code;
				$("#chengshi").html(name);
				$("#city-modal").modal("close");
				//选择完更新缓存
				var jj = {"org_code" : quCode, "org_name" : name};
  			  	App.setUseCity(jj);
			});
	       	
       	}, function ( desc ) {
            Result.alert( "对不起:" + desc );
        }, function ( err ) {
            Result.alert( "错误:" + JSON.stringify(err));
        } );
	 }
	 
	 
	 function tijiao(){
		 var zhandui_name = $("#zhandui_name").val();
		 if(zhandui_name == null || zhandui_name == ""){
			 alert("请输入战队名称");
			 return;
		 }
		 var baoming = $("#cansan_list").find("input[name='bao_id[]']");
		 var isFlag = true;
		 var isPhone = true;
		 var values=[];
		 baoming.each(function(i, obj){
			 if($(obj).val() == null || $(obj).val() == ""){
				 isFlag = false;
			 }
			 var val = $(obj).val();
			 if(val.length != 11 || !/^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/.test( val )){
				 isPhone = false;
		     }
			 values.push($(obj).val());
		 });
		 if(!isFlag){
			 alert("您还有主力成员游戏ID未填写，请补充");
			 return;
		 }
		 if(!isPhone){
			 alert("主力成员游戏ID填写有误，请重新填写");
			 return;
		 }
		 var params = {};
		 params.mobiles=values.toString();
		 params.match_id = race_id;
		 params.user_id = global_param_map['id'];
		 params.crops_name = zhandui_name;
		 params.org_code = quCode;
		 params.match_reg_fee = detailObj.reg_fee;
		 Result.doResult( {
			 url:  Interface.zs.matchMatchRegOrder,
			 data: params,
			 type: "POST",
			 async: false,
		 }, function ( data ) {
			 if(detailObj.reg_fee > 0){
				 $("#fee1").html(detailObj.reg_fee);
				 $('#pay-modal').modal({'closeViaDimmer':0,'width':760,'height':'488'});
				 $("#cp_order").val(data.cp_order);
			 } else {
				 alert("报名成功");
				 setTimeout(function () {
					 Result.forward("raceDetail.html", {"race_id" : race_id});
		 		 }, 200);
			 }
			 
		 }, function ( desc ) {
			 Result.alert( "对不起:" + desc);
			 console.log(desc);
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
	 }
	 
	 
	 function loadDetail(){
		 Result.doResult( {
			 url:  Interface.zs.matchGetMatchDetail,
			 data: {"match_id" : race_id, "user_id" : global_param_map['id']},
			 type: "POST",
			 async: false,
		 }, function ( data ) {
			 detailObj = data;
			 Result.fillData( $("#detail_content"), data, "field" );
			 $("#bg_icon").attr("src", Interface.image.pre + data.matchType.detail_icon);
			 $("#iconimg100").attr("src", Interface.image.pre + data.matchType.match_icon);
			 $("#xiangmu_soan").html(data.matchType.name);
			 
			 var person = parseInt(data.match_need_num);
			 if(person > 0){
				 var p = parseInt(person / 2);
				 for(var i=0;i<p;i++){
					 $("#cansan_list").append($("#two_template").clone().removeAttr("id"));
				 }
				 if((person % 2) != 0){
					 $("#cansan_list").append($("#one_template").clone().removeAttr("id"));
				 }
			 }
			 
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
	 }
	 
	 
	 window.replaceLogo = function ( $field, logo, rowVal ) {
		$field.attr("src", Interface.image.pre + rowVal['userIcon']);
	 };
	 
	 window.replaceRegFee = function ( $field, fee, rowVal ) {
		if(fee == null || fee == 0 || fee == ""){
		} else {
			$field.html("&yen;" + fee);
		}
	 };
	 window.replaceRefereeMode = function ( $field, mode, rowVal ) {
		 if(mode == 1){
			 $field.html("自裁模式");
		 } else {
			 $field.html("裁判模式");
		 }
	 };
	 
	 
	 
		 
	
}( window ) );
